package com.nbsaas.boot.interceptor;

import com.nbsaas.boot.monitor.ApiLogEvent;
import com.nbsaas.boot.monitor.ApiMonitorDisruptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
public class ApiMonitorInterceptor implements HandlerInterceptor {

    private final ApiMonitorDisruptor disruptor;

    private static final String START_TIME_ATTR = "monitorStartTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute(START_TIME_ATTR, System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        Object startTimeObj = request.getAttribute(START_TIME_ATTR);
        if (startTimeObj instanceof Long startTime) {
            long duration = System.currentTimeMillis() - startTime;

            ApiLogEvent log = new ApiLogEvent();
            log.setUri(request.getRequestURI());
            log.setMethod(request.getMethod());
            log.setStartTime(startTime);
            log.setDuration(duration);
            log.setStatus(response.getStatus());
            log.setSuccess(response.getStatus() < 400);
            log.setTenantId(request.getHeader("X-Tenant-Id")); // 多租户Header识别

            disruptor.publish(log); // 异步非阻塞
        }
    }
}
